package com.itheima.plantform.filter;


import com.itheima.plantform.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("经过第三个过滤器");
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //3.判断当前的请求是否为登录请求,如果是,则直接放行
        if (request.getURI().getPath().contains("/api/user/login")){
            //放行
            return chain.filter(exchange);
        }
        //如果不是登录请求
        //2否则，判断cookie中是否存在信息，没有的话，拒绝访问
        String jtiFromCookie = this.getJtiFromCookie(request);

        if(StringUtils.isEmpty(jtiFromCookie)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3.判断redis中令牌是否存在，没有的话，拒绝访问
        String token = (String) redisTemplate.boundValueOps("token"+jtiFromCookie).get();
        if(StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.2 如果令牌合法,则放行
        return chain.filter(exchange);
    }

    /**
     * 查看cookie中jti是否存在
     * @param request
     * @return
     */

    private String getJtiFromCookie(ServerHttpRequest request) {
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie cookie = cookies.getFirst("uid");
        if(cookie!=null){
            return cookie.getValue();
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
